{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[5.26711107e-02 5.00012402e-02 5.00000001e-02 ... 1.82966918e+01\n",
      "  5.00000001e-02 5.00000088e-02]\n",
      " [5.00000001e-02 5.00000009e-02 5.00000003e-02 ... 5.49241669e+01\n",
      "  5.00000007e-02 4.59445651e+01]\n",
      " [5.00000000e-02 5.00000000e-02 5.00000000e-02 ... 5.00000000e-02\n",
      "  5.00000000e-02 5.00000000e-02]\n",
      " ...\n",
      " [8.48849772e+02 7.26564429e+01 5.77904952e+01 ... 8.09619737e-02\n",
      "  1.34316105e+02 4.76862855e+00]\n",
      " [5.00000002e-02 2.45559358e+01 5.00000003e-02 ... 8.01424988e+01\n",
      "  1.47292826e+01 1.60365357e+00]\n",
      " [5.00000003e-02 4.39046309e+01 5.00000004e-02 ... 1.43061475e+02\n",
      "  5.00000006e-02 5.00000027e-02]]\n",
      "[[2.08333335e-03 2.08333339e-03 2.08333333e-03 ... 2.08333337e-03\n",
      "  2.08333336e-03 8.83289592e-01]\n",
      " [2.50000010e-03 2.50000006e-03 2.50000000e-03 ... 2.50000004e-03\n",
      "  2.50000002e-03 3.31806711e-01]\n",
      " [6.02409646e-04 6.02409661e-04 6.02409639e-04 ... 6.02409646e-04\n",
      "  6.02409646e-04 7.69809396e-01]\n",
      " ...\n",
      " [4.54545481e-03 4.54545465e-03 4.54545455e-03 ... 4.54545455e-03\n",
      "  4.54545463e-03 4.62659644e-01]\n",
      " [2.94117650e-03 3.77464512e-01 2.94117647e-03 ... 2.94117650e-03\n",
      "  2.94117654e-03 2.94117654e-03]\n",
      " [2.31567948e-01 3.57142862e-03 3.57142857e-03 ... 3.57142874e-03\n",
      "  3.57142864e-03 4.53221403e-01]]\n"
     ]
    }
   ],
   "source": [
    "from sklearn.datasets import fetch_20newsgroups\n",
    "from sklearn.feature_extraction.text import CountVectorizer\n",
    "from sklearn.decomposition import LatentDirichletAllocation\n",
    " \n",
    "\n",
    "# 使用remove去除正文以外的信息\n",
    "data = fetch_20newsgroups(remove=('headers', 'footers', 'quotes'))\n",
    "max_features = 1000\n",
    "# 将文本数据变换为向量\n",
    "tf_vectorizer = CountVectorizer(max_features=max_features,\n",
    "stop_words='english')\n",
    "tf = tf_vectorizer.fit_transform(data.data)\n",
    "n_topics = 20\n",
    "model = LatentDirichletAllocation(n_components=n_topics)\n",
    "model.fit(tf)\n",
    "print(model.components_) # 各主题包含的单词的分布 \n",
    "print(model.transform(tf)) # 使用主题描述的文本"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
